<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>我的关注</title>
    <link rel="stylesheet" href="css/relation.css">

</head>

<body>
    <!-- 导航栏 -->
    <div class="nav">
        <img src="img/logo.jpg" alt="">
        <span class="title">博客系统</span>
        <!-- 用来占据中间位置 -->
        <span class="spacer" style="width: 45%"></span>
        <a href="blog_list.html">博客广场</a>
        <a href="myblog_list.html">个人博客</a>
        <a href="personal_center.html">个人中心</a>
        <a href="my_relation_following.html">我的关注/粉丝</a>
        <a href="private_message.html">聊天室</a>
        <a href="draft_list.html">我的草稿</a>
        <a href="blog_add.html">写博客</a>
        <a href="javascript:logout()">注销</a>
    </div>

    <!-- 版心 -->
    <div class="container">
        <div class="container-left">
            <div class="card">
                <img id="avatar-img" src="img/avatar.png" class="avtar" alt="Avatar">
                <h3 id="author2">赵六</h3>

                <a id="url" href="#" target="_blank">gitee 地址</a>
                <!-- <div class="counter">
                    <span class="icon icon-counter"></span>
                    <span id="counter">文章数量：0</span>
                </div> -->
                <div class="reading-times">
                    <span class="icon icon-reading"></span>
                    <span id="reading-times">总访问量：9999</span>
                </div>
                <div class="comment-times">
                    <span class="icon icon-comment"></span>
                    <span id="comment-times">获得评论：2 次</span>
                </div>

            </div>
        </div>

        <!-- 右侧内容详情 -->
        <div id="relationship" class="container-right">
            <div class="relation-tab">
                <!-- 会话列表标签 -->
                <div class="following-tab">我的关注</div>
                <!-- 好友列表标签 -->
                <div class="follows-tab active" onclick="toFollows()">我的粉丝</div>
            </div>

            <div class="relation-list" id="following-list">
                <!-- 关注列表，根据数据库内容动态展示 -->

                <!-- <div class="relation">
                    <img class="avtar" src="img/avatar.png" alt="Avatar">
                    <h3 class="username" user-id="1">张三</h3>
                    <button class="attention-button"> 已关注 </button>
                    <span class="more-options">
                        <a class="options-icon" title="更多">&#8942;</a>
                        <div class="options-content">
                            <a class="private-message-link" href="#">私信</a>
                        </div>
                    </span>
                </div>

                <div class="relation">
                    <img class="avtar" src="img/avatar.png" alt="Avatar">
                    <h3 class="username" user-id="2">李四</h3>
                    <button class="attention-button"> 已关注 </button>
                    <span class="more-options">
                        <a class="options-icon" title="更多">&#8942;</a>
                        <div class="options-content">
                            <a class="private-message-link" href="#">私信</a>
                        </div>
                    </span>
                </div> -->


            </div>
        </div>

    </div>>

    <script src="./js/jquery.min.js"></script>
    <script src="./js/logout.js"></script>
    <script>
        function toFollows() {
            location.href = "my_relation_follows.html";
        }

        // 获取用户信息
        function getUserInfo() {
            jQuery.ajax({
                url: "user/getuserinfo",
                type: "POST",
                data: {},
                success: function (res) {
                    if (res.code == 200 && res.data != null && res.data.id > 0) {
                        // 获取用户信息成功！
                        // 头像
                        if (res.data.photo != null && res.data.photo != '') {
                            jQuery("#avatar-img").attr("src", "/photo/" + res.data.photo);
                        } else {
                            jQuery("#avatar-img").attr("src", "/img/avatar.png");
                        }

                        // 用户名或昵称
                        if (res.data.nickname != null && res.data.nickname != 'undefined') {
                            jQuery("#author2").html(res.data.nickname);
                        } else {
                            jQuery("#author2").html(res.data.username);
                        }

                        // gitee地址
                        if (res.data.gitee != null && res.data.gitee != '') {
                            jQuery("#url").attr("href", res.data.gitee);
                        } else {
                            console.log("该作者未设置gitee地址！");
                        }

                        // 获取总访问量和评论总数
                        getTotalRCountAndCommentByUId(res.data.id);


                        // 获取关注列表
                        getFollowingList(res.data.id);

                    } else {
                        alert("获取作者信息失败！");
                        location.href = "blog_list.html";
                    }
                }
            });
        }

        getUserInfo();

        //根据指定用户获取总访问量和评论总数
        function getTotalRCountAndCommentByUId(uid) {
            jQuery.ajax({
                url: "user/get_total_rcount_and_comment",
                type: "POST",
                data: {
                    "uid": uid
                },
                success: function (res) {
                    if (res.code == 200 && res.data != null) {
                        jQuery("#reading-times").html("总访问量：" + res.data.rCounts);
                        jQuery("#comment-times").html("获得评论：" + res.data.comments + "次");
                    } else {
                        console.log("获取失败！" + res.msg);
                    }
                }
            });
        }


        function getFollowingList(userId) {
            console.log("getFollowingList: " + userId);
            jQuery.ajax({
                url: "follow/get_following_list",
                type: "POST",
                data: {
                    "userId": userId
                },
                success: function (res) {
                    if (res.code == 200) {
                        if (res.data.length > 0) {
                            // 成功获取到关注列表
                            var followingListHtml = "";
                            for (var i = 0; i < res.data.length; ++i) {
                                var item = res.data[i];
                                followingListHtml += '<div class="relation">';

                                if (item.photo != null && item.photo != '') {
                                    followingListHtml += '<img class="avtar" src="/photo/' + item.photo + '" alt="Avatar">';
                                } else {
                                    followingListHtml += '<img class="avtar" src="img/avatar.png" alt="Avatar">';
                                }

                                followingListHtml += '<h3 class="username" user-id="' + item.followingId + '">';

                                if (item.nickname != null && item.nickname != 'undefined') {
                                    followingListHtml += '' + item.nickname + '</h3>';
                                } else {
                                    followingListHtml += '' + item.username + '</h3>';
                                }
                                followingListHtml += '<button class="attention-button"> 已关注 </button>';
                                followingListHtml += '<span class="more-options">';
                                followingListHtml += '<a class="options-icon" title="更多">&#8942;</a>';
                                followingListHtml += '<div class="options-content">';
                                followingListHtml += '<a class="private-message-link" href="#">私信</a>';
                                followingListHtml += '</div>'
                                followingListHtml += '</span>'
                                followingListHtml += '</div>'
                            }
                            jQuery("#following-list").html(followingListHtml);
                            // 调用函数，设置私信链接
                            setPrivateMessageLinks();

                            // 在页面加载完成后调用 bindFollowButtons 函数
                            bindFollowButtons();

                            // 添加点击事件到所有的username
                            bindUsernameClickEvents();
                            
                        } else if (res.data.length == 0) {
                            // 暂无关注作者
                            jQuery("#relation-list").html("<h2 style = 'margin-left:100px;margin-top:100px'>暂无关注作者！</h2>")
                        }
                    } else {
                        alert("获取关注列表失败！" + res.msg);
                        location.href = "blog_list.html";
                    }
                }
            });
        }


        // 为所有标签设置私信链接
        function setPrivateMessageLinks() {
            const privateMessageLinks = document.querySelectorAll(".private-message-link");

            privateMessageLinks.forEach(link => {
                const userId = link.closest(".relation").querySelector(".username").getAttribute("user-id");
                link.href = `private_message.html?uid=${userId}`;
            });
        }

        // 在页面加载完成后调用这个函数，将关注按钮的点击事件绑定
        function bindFollowButtons() {
            const attentionButtons = document.querySelectorAll(".attention-button");
            attentionButtons.forEach(button => {
                button.addEventListener("click", toggleFollow);
            });
        }

        // 点击关注按钮时触发的函数
        function toggleFollow(event) {
            const button = event.target;
            const relationDiv = button.closest(".relation");
            const followingId = relationDiv.querySelector(".username").getAttribute("user-id");
            const isFollowed = button.textContent.trim() === "已关注";

            // 在这里根据 isFollowed 的值来执行关注或取消关注的逻辑
            if (isFollowed) {
                // 执行取消关注逻辑，通过发送 AJAX 请求给服务器
                // 然后根据返回结果来更新按钮和状态
                cancelFollow(followingId);
            } else {
                // 执行关注逻辑，可以通过发送 AJAX 请求给服务器
                // 然后根据返回结果来更新按钮和状态
                follow(followingId);

            }
        }

        // 取消关注函数
        function cancelFollow(followingId) {
            console.log("cancelFollow: " + followingId);
            // 发送取消关注的 AJAX 请求
            jQuery.ajax({
                url: "follow/del_follow_relationship",
                type: "POST",
                data: {
                    "followingId": followingId
                },
                success: function (res) {
                    if (res.code == 200 && res.data == 1) {
                        // 取消关注成功 
                        // 更新按钮状态
                        updateButtonState(followingId, false); // 将按钮状态设置为未关注
                    } else {
                        alert("取消关注失败！" + res.msg);
                    }
                }
            });
        }

        // 关注函数
        function follow(followingId) {
            console.log("follow: " + followingId);
            // 发送关注的 AJAX 请求
            jQuery.ajax({
                url: "follow/add_follow_relationship",
                type: "POST",
                data: {
                    "followingId": followingId
                },
                success: function (res) {
                    if (res.code == 200 && res.data == 1) {
                        // 关注成功 
                        // 更新按钮状态
                        updateButtonState(followingId, true); // 将按钮状态设置为已关注
                    } else if (res.code == 200 && res.data == 0) {
                        alert("已经关注了该用户！");
                    } else {
                        alert("关注失败！" + res.msg);
                    }
                }
            });
        }

        // 更新按钮状态的函数
        function updateButtonState(userId, isFollowed) {
            const relationDiv = document.querySelector(`.username[user-id="${userId}"]`).closest(".relation");
            const button = relationDiv.querySelector(".attention-button");

            if (isFollowed) {
                button.textContent = "已关注";
            } else {
                button.textContent = "关注";
            }
        }

        // 添加点击事件到所有的username
        function bindUsernameClickEvents() {
            const usernames = document.querySelectorAll(".username");
            usernames.forEach(username => {
                const userId = username.getAttribute("user-id");
                username.addEventListener("click", function () {
                    toPersonPage(userId);
                });
            });
        }

        // 跳转到用户主页函数
        function toPersonPage(uid) {
            var url = "personal_page.html?uid=" + uid;
            console.log("url:" + url);
            window.open(url, '_blank');
        }
    </script>

</body>

</html>